package ru.nsu.fit.ask_joe.user_interface_manager.realization;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import ru.nsu.fit.ask_joe.MainManager;
import ru.nsu.fit.ask_joe.R;
import ru.nsu.fit.ask_joe.user_interface_manager.interfaces.IPanel;
import ru.nsu.fit.client.core.response.KernelResponse;

import java.util.ArrayList;
import java.util.List;

public class AskJoePanel implements IPanel {
	
	private static final int resourceId = R.layout.ask_joe;
	
	private final View _view;
    private final EditText _editQuestion;
    private final EditText[] _editAnswer = new EditText[5];
    private final Button _buttonBack, _buttonSend;
    private ProgressDialog _progressDialog;

    private class ResponseProcesser extends KernelResponseProcessor {

        @Override
        protected void onPostExecute(KernelResponse result) {
            super.onPostExecute(result);
            if (_progressDialog != null)
            {
                _progressDialog.dismiss();
                _progressDialog = null;
            }
            if (result.isSuccessful())
            {
                MainManager.getUserInterfaceManager().setCurrentPanel(new MyQuestionPanel());
            }
            else
            {
                AlertDialog.Builder builder =  new AlertDialog.Builder(getView().getContext());
                builder.setTitle(getView().getContext().getString(R.string.Message_SendingError));
                builder.setMessage(result.getErrorText()); //TODO translate error message into current language
                builder.setPositiveButton(getView().getContext().getString(R.string.Button_Ok), null);
                builder.show();
            }
        }
    }
	public AskJoePanel()
	{
		_view = MainManager.getUserInterfaceManager().getMainActivity().getLayoutInflater().inflate(resourceId, null);

        _editQuestion = (EditText)_view.findViewById(R.id.edit_question);
        _editAnswer[0] = (EditText)_view.findViewById(R.id.edit_answer1);
        _editAnswer[1] = (EditText)_view.findViewById(R.id.edit_answer2);
        _editAnswer[2] = (EditText)_view.findViewById(R.id.edit_answer3);
        _editAnswer[3] = (EditText)_view.findViewById(R.id.edit_answer4);
        _editAnswer[4] = (EditText)_view.findViewById(R.id.edit_answer5);

        _editAnswer[0].addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
            public void afterTextChanged(Editable editable) {
                updateVisibleAnswers(0);
            }
        });
        _editAnswer[1].addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
            public void afterTextChanged(Editable editable) {
                updateVisibleAnswers(1);
            }
        });
        _editAnswer[2].addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
            public void afterTextChanged(Editable editable) {
                updateVisibleAnswers(2);
            }
        });
        _editAnswer[3].addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
            public void afterTextChanged(Editable editable) {
                updateVisibleAnswers(3);
            }
        });
        _editAnswer[4].addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {}
            public void afterTextChanged(Editable editable) {
                updateVisibleAnswers(4);
            }
        });
        updateVisibleAnswers(0);

        _buttonBack = (Button)_view.findViewById(R.id.button_back);
		_buttonBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
		        MainManager.getUserInterfaceManager().setCurrentPanel(new MyQuestionPanel());
			}
		});
		
		_buttonSend = (Button)_view.findViewById(R.id.button_send);
        _buttonSend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onSendClick(v);
            }
        });
	}

    private void onSendClick(View v)
    {
        if (_editQuestion.getText().toString().equals("") || _editAnswer[0].getText().toString().equals(""))
        {
            AlertDialog.Builder builder =  new AlertDialog.Builder(getView().getContext());
            builder.setTitle(getView().getContext().getString(R.string.Message_SendingError));
            builder.setMessage(getView().getContext().getString(R.string.Message_EmptyQuestionOrAnswer));
            builder.setPositiveButton(getView().getContext().getString(R.string.Button_Ok), null);
            builder.show();
            return;
        }

        MainManager.getUserInterfaceManager().setStatistics(null);

        try {
            final List<String> answers = new ArrayList<String>();
            for (int i = 0; i < _editAnswer.length; i++)
            {
                if (_editAnswer[i].getText().toString().equals(""))
                    break;
                answers.add(_editAnswer[i].getText().toString());
            }
            final int id = MainManager.getClientKernel().sendQuestion(_editQuestion.getText().toString(), answers);
            _progressDialog = ProgressDialog.show(v.getContext(), v.getContext().getString(R.string.Message_PleaseWait), v.getContext().getString(R.string.Message_Sending));

            new ResponseProcesser().execute(id);
        } catch (Exception e) {
            MainManager.getLogManager().getLogger().printError(e.getMessage());
        }
    }

    private void updateVisibleAnswers(int n)
    {
        if (_editAnswer[n].getText().toString().equals(""))
        {
            for (int i = n+1; i < _editAnswer.length; i++)
            {
                _editAnswer[i].setVisibility(View.INVISIBLE);
            }
        }
        else if (n + 1 < _editAnswer.length)
        {
            _editAnswer[n + 1].setVisibility(View.VISIBLE);
            updateVisibleAnswers(n + 1);
        }
    }
	
	@Override
	public View getView() {
		return _view;
	}
}
